package org.voyager.service.admin.scenic.service.impl;

import com.alibaba.fastjson.JSONObject;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.voyager.common.beans.JsonResult;
import org.voyager.service.admin.scenic.service.LbsService;
import org.voyager.service.admin.scenic.vo.GeoConvertVo;

import java.util.Objects;

@Service
public class LbsServiceImpl implements LbsService {
    private static final Logger logger = LoggerFactory.getLogger(LbsServiceImpl.class);

    @Value(value = "${lbs.baidu.url}")
    private String lbsBaiduUrl;
    @Value(value = "${lbs.baidu.ak}")
    private String lbsBaiduAk;

    @Override
    public JsonResult geoConvert(GeoConvertVo geoConvertVo) {
        String url = lbsBaiduUrl + "?" + "coords=" + geoConvertVo.getCoords();

        url += "&from=" + (StringUtils.isEmpty(geoConvertVo.getFrom()) ? "3" : geoConvertVo.getFrom());
        url += "&to=" + (StringUtils.isEmpty(geoConvertVo.getTo()) ? "5" : geoConvertVo.getFrom());
        url += "&ak=" + (StringUtils.isEmpty(geoConvertVo.getAk()) ? lbsBaiduAk : geoConvertVo.getAk());

                Request request = new Request.Builder()
                .url(url)
                .build();

        OkHttpClient okHttpClient = new OkHttpClient();

        try {
            Response response = okHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                String responseBody = response.body().string();
                JSONObject result = JSONObject.parseObject(responseBody);
                if (Objects.equals(0, result.get("status"))) {
                    return JsonResult.ok().putData("result", result.get("result"));
                } else {
                    return JsonResult.error(result.getInteger("status"), result.getString("message"));
                }
            } else {
                return JsonResult.error(response.code(), response.message());
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("baidu; " + e.getMessage());
            return JsonResult.error("转换地图坐标出错!");
        }
    }
}
